package code.part04_collection;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * @author: ZJT
 * @Time: 2021/7/19
 * @Description: Iterator
 */
public class P03_Iterator {

    @Test
    public void run() {

        ArrayList list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        //迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object o = iterator.next();
            if (o.equals(1)) {
                iterator.remove();
            }
            System.out.println(o);
        }
    }

    @Test
    public void run2() {
        ArrayList list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        ListIterator iterator = list.listIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        //当使用向前遍历的时候必须要保证指针位置
        while (iterator.hasPrevious()) {
            System.out.println(iterator.previous());
        }
    }
}
